#!/usr/bin/env bash
# IuVe Connect Agent Console host (Phase C.3).
# Starts loopback ui_bridge if needed and opens the Console UI.
set -euo pipefail

CONTENTS_DIR="$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)"
RESOURCES="$CONTENTS_DIR/Resources"
APP_HOME="$(CDPATH= cd -- "$CONTENTS_DIR/.." && pwd)"

resolve_agent_root() {
  if [ -f "$RESOURCES/agent_root.path" ]; then
    root="$(tr -d '\r\n' < "$RESOURCES/agent_root.path")"
    if [ -n "$root" ] && [ -d "$root" ]; then
      printf '%s\n' "$root"
      return 0
    fi
  fi
  # App shipped under /opt/.../Applications/IuVe Connect Agent.app
  parent="$(CDPATH= cd -- "$APP_HOME/.." && pwd)"
  if [ -d "$parent/iuve_connect_agents" ]; then
    printf '%s\n' "$parent"
    return 0
  fi
  if [ -d "/opt/iuve-connect-desktop-agent/iuve_connect_agents" ]; then
    printf '%s\n' "/opt/iuve-connect-desktop-agent"
    return 0
  fi
  return 1
}

if ! AGENT_ROOT="$(resolve_agent_root)"; then
  /usr/bin/osascript -e 'display alert "IuVe Connect Agent" message "Agent root not found. Install to /opt/iuve-connect-desktop-agent or set Contents/Resources/agent_root.path." as critical' >/dev/null 2>&1 || true
  exit 1
fi

CONFIG_PATH="${HOME}/.config/iuve-connect-agent/desktop-config.json"
mkdir -p "${HOME}/.config/iuve-connect-agent"

BUNDLED_PYTHON="$AGENT_ROOT/runtime/python/bin/python3"
if [ -x "$BUNDLED_PYTHON" ]; then
  PYTHON_EXE="$BUNDLED_PYTHON"
elif [ -n "${IUVE_AGENT_PYTHON:-}" ] && [ -x "${IUVE_AGENT_PYTHON}" ]; then
  PYTHON_EXE="${IUVE_AGENT_PYTHON}"
elif command -v python3 >/dev/null 2>&1; then
  PYTHON_EXE="$(command -v python3)"
else
  /usr/bin/osascript -e 'display alert "IuVe Connect Agent" message "Python runtime not found." as critical' >/dev/null 2>&1 || true
  exit 1
fi

export PYTHONPATH="$AGENT_ROOT/vendor:$AGENT_ROOT${PYTHONPATH:+:$PYTHONPATH}"
export IUVE_AGENT_PYTHON="$PYTHON_EXE"
export IUVE_UI_BRIDGE_HOST="${IUVE_UI_BRIDGE_HOST:-127.0.0.1}"
export IUVE_UI_BRIDGE_PORT="${IUVE_UI_BRIDGE_PORT:-8765}"

cd "$AGENT_ROOT"
# Prefer system browser from .app (pywebview optional; --no-webview keeps Dock app responsive).
exec "$PYTHON_EXE" -m iuve_connect_agents.desktop.ui_bridge \
  --launch-console \
  --no-webview \
  --config "$CONFIG_PATH"
